#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size(), j = 0, intmin = -0x3f3f3f3f;
        vector<vector<int>> f(n, vector<int>(3)), g(n, vector<int>(3));

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (i == 0 && j == 0) f[0][0] = -prices[0], g[0][0] = 0;
                else if (i == 0 && j > 0) f[i][j] = g[i][j] = intmin;
                else
                {
                    f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                    g[i][j] = g[i - 1][j];
                    if (j - 1 >= 0) g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
                }
            }
        }
        int ma = 0;
        for (int j = 0; j <= 2; j++)
        {
            ma = max(ma, g[n - 1][j]);
        }

        return ma;
    }
};